from Tkinter import *
import os
import tkFileDialog
import shutil
import arcpy
from arcpy import env
arcpy.env.overwriteOutput = True


class CustomerFinder(Frame):
   
   filePath = ""
   runTime = 0
   result_path = os.path.abspath('Result/')
   selectionQuerys = []
   time_pickup_start = []
   time_pickup_end = []
   
   featuresList = []
   dataVar = 1
   wkdayData = ['400_553_wkday_Buffer_prj.shp',
             '554_849_wkday_Buffer_prj.shp',
             '850_1259_wkday_Buffer_prj.shp',
             '1300_1539_wkday_Buffer_prj.shp',
             '1540_2003_wkday_Buffer_prj.shp',
             '2004_2200_wkday_Buffer_prj.shp',
             '2201_2759_wkday_Buffer_prj.shp'
             ]

   satData = ['400_759_sat_Buffer_prj.shp',
           '800_2059_sat_Buffer_prj.shp',
           '2100_2759_sat_Buffer_prj.shp'
           ]
   sunData = ['400_759_sun_buffer_prj.shp',
           '800_2059_sun_buffer_prj.shp',
           '2100_2759_sun_buffer_prj.shp'
           ]
   
   
   def cleanup(self):
       for node in self.featuresList:
          # print 'node' + node
           arcpy.DeleteFeatures_management(node)
           #arcpy.delete
           
       
   def clear(self):
       self.consoleText['text'] = ''
   
   
   def start(self):
      featuresList = []
      """self.filePath = os.path.abspath("Data.dbf")
      self.TitleLabel = Label(self,text='')
      self.TitleLabel.grid(row=0,columnspan=2)"""
      self.outputLabel = Label(self, width=15 , anchor="n")
      self.outputLabel['text'] = "Result Path: "
      self.outputLabel.grid(row=0, column=0, sticky=N + W)
      
      self.outputPathText = Label(self, width=50)
      self.outputPathText.grid(row=0, column=1, sticky=W + E + N)
      self.outputPathText['text'] = self.result_path
      
  
      self.fileLabel = Label(self, width=15 , anchor="n")
      self.fileLabel['text'] = "Data File: "
      self.fileLabel.grid(row=1, column=0, sticky=N + W)
      
      self.filePathText = Label(self, width=50 , text='C:\\')
      self.filePathText.grid(row=1, column=1, sticky=W + E + N)
      self.filePathText['text'] = self.filePath
      
      self.loadFileBtn = Button(self, text='Load File', command=self.loadFile)
      self.loadFileBtn.grid(row=2, column=0, sticky=W + E + N + S)
      
      self.resultFileBtn = Button(self, text='Save to..', command=self.selectResultFolder)
      self.resultFileBtn.grid(row=3, column=0, sticky=W + E + N + S)
      
      self.runBtn = Button(self, text='Run', command=self.run)
      self.runBtn.grid(row=4, column=0, sticky=W + E + N + S)

      self.clearConsoleBtn = Button(self, text='Clear console', command=self.clear)
      self.clearConsoleBtn.grid(row=5, column=0, sticky=W + E + N + S)
      
      self.bLabel = Label(self, text='Please Select the date', anchor="n")
      self.bLabel.grid(row=6, column=0, sticky=W + E + N + S)

      """R2 = Radiobutton(root, text="Option 2", variable=var, value=2,
                  command=sel)"""
   
      self.r1 = Radiobutton(self, text='Weekday', value=1, anchor='w', command=self.day_change_weekday)
      self.r1.grid(row=6, column=0, sticky=W + E + N + S)

      self.r2 = Radiobutton(self, text='Saturday', value=2, anchor='w', command=self.day_change_saturday)
      self.r2.grid(row=7, column=0, sticky=W + E + N + S)

      self.r3 = Radiobutton(self, text='Sunday', value=3, anchor='w', command=self.day_change_sunday)
      self.r3.grid(row=8, column=0, sticky=W + E + N + S)

      self.dayLabel = Label(self, text='', anchor="w")
      self.dayLabel.grid(row=9, column=0, sticky=W + E + N + S)

      """self.consoleText = Text( self,height=10)
      sel.consoleText.grid( row =2, column =1, rowspan=4,sticky = W+E+N+S  )"""
      
      self.consoleTextTitle = Label(self, text='Console:', anchor="nw")
      self.consoleTextTitle.grid(row=2, column=1, sticky=W + E + N + S)

      self.consoleText = Label(self, text='', anchor="nw", justify='left')
      self.consoleText.grid(row=3, column=1, rowspan=8, sticky=W + E + N + S)
      
      for root, dirs, files in os.walk('Output'):
          for f in files:
              os.unlink(os.path.join(root, f))
          for d in dirs:
              shutil.rmtree(os.path.join(root, d))
    
      for root, dirs, files in os.walk('Result'):
          for f in files:
              os.unlink(os.path.join(root, f))
          for d in dirs:
              shutil.rmtree(os.path.join(root, d))
      
      """Clean Output Folder"""
   
   def __init__(self, master=None):
       Frame.__init__(self , master)
       self.master.title("CustomerFinder")      
       self.master.rowconfigure(0, weight=1)
       self.master.columnconfigure(0, weight=1)
       self.dateVar = 1
       self.grid(sticky=W + E + N + S)
       self.start()
       
         
   
   def getTimes(self, day, file1):
      timePath = os.path.abspath(file1)
      timeFile = open(timePath, 'r')
      timeContent = timeFile.read()
      #print len(timeContent.split('SeperateLine\n'))
      wkListSt = []
      wkListEnd = []
      weListSt = []
      weListEnd = []
      wkStr, weStr = timeContent.split('\nSeperateLine\n')[0], timeContent.split('SeperateLine\n')[1]
      
      wkTimesStr = wkStr[wkStr.find('Weekdays:') + len('Weekdays:\n'):wkStr.find('\nEnd')].split('\n')
      weTimesStr = weStr[weStr.find('\nWeekends:') + len('\nWeekends:\n'):weStr.find('\nEnd', weStr.find('\nEnd'))].split('\n')

      #print weTimesStr
      for node in wkTimesStr:
            time1, time2 = node.split(',')
            wkListSt.append(time1)
            wkListEnd.append(time2)
     # print 'Week',wkListSt,wkListEnd
      for node1 in weTimesStr:
            time1, time2 = node1.split(',')
            weListSt.append(time1)
            weListEnd.append(time2)
    #  print 'End',weListSt,weListEnd
      if day == 'weekday':
            return wkListSt, wkListEnd
      elif day == 'weekend':
            return weListSt, weListEnd

   
   
   def loadFile(self):
       self.filePath = tkFileDialog.askopenfilename()
       self.filePathText['text'] = self.filePath      
   
   def selectResultFolder(self):
       self.result_path = tkFileDialog.askdirectory()
       self.outputPathText['text'] = self.result_path
       if not os.path.exists(self.result_path):
#           print self.result_path
           os.makedirs(self.result_path)
       
   def print_console(self, content):
      if(len(self.consoleText["text"].split("\n")) >= 11):
            self.consoleText["text"] = self.consoleText['text'][self.consoleText['text'].find("\n") + 1:]
      self.consoleText["text"] = self.consoleText['text'] + content + '\n'
      #print len(self.consoleText['text'].split('\n'))
      


   def day_change_weekday(self):
      self.dataVar = 1
      self.dayLabel['text'] = 'Weekday'

   def day_change_saturday(self):
      self.dataVar = 2
      self.dayLabel['text'] = 'Saturday'

   def day_change_sunday(self):
      self.dataVar = 3
      self.dayLabel['text'] = 'Sunday'
      
   def run(self):
       
       #self.outputPath = os.path.abspath("Output")
    
       self.outputPath = os.path.join(os.path.abspath("Output"),'fol'+'a'*self.runTime+'der')

       if not os.path.exists(self.outputPath):
           print 'OutputPath' + self.outputPath
#           print self.result_path
           try:
               os.makedirs(self.outputPath)
           except OSError as exc: # Python >2.5
               if exc.errno == errno.EEXIST:
                   pass
               else: raise
       if self.dataVar == 1:    #Day1
          self.time_pickup_start, self.time_pickup_end = self.getTimes('weekday', 'Times.txt')
          #print (self.time_pickup_start)
          #print (self.time_pickup_end)
       else:
          self.time_pickup_start, self.time_pickup_end = self.getTimes('weekend', 'Times.txt')
       for i in range(len(self.time_pickup_start)):
           selectionQuery1 = "\"d_o_time\"" + " >= " + "'" + self.time_pickup_start[i] + "'" 
           selectionQuery2 = "\"d_o_time\"" + " < " + "'" + self.time_pickup_end[i] + "'" 
           self.selectionQuerys.append(selectionQuery1 + " AND " + selectionQuery2)
       #print 'The selction queries used are:\n'
       for s in self.selectionQuerys:
           self.print_console(s)
           #print s
       
       try:
           x_coords = "LONG1"
           y_coords = "LAT1"
           z_coords = None
           out_Layer = "customer"
           saved_Layer = os.path.join(self.outputPath, 'customerLayer.lyr')
           spRef = r"Coordinate Systems\Geographic Coordinate Systems\North America\NAD 1983.prj"
           #print 'FilePath: ' + os.path.normpath(self.filePath)
           #print 'Saved Layer: ' + saved_Layer          
           arcpy.MakeXYEventLayer_management(os.path.normpath(self.filePath), x_coords, y_coords, out_Layer, spRef, z_coords)
          # print 'out_Layer: ' + str(arcpy.GetCount_management(out_Layer))
           arcpy.SaveToLayerFile_management(out_Layer, saved_Layer) 
       except:
           print arcpy.GetMessages()
       customLayname = []
       self.print_console("Loading Customer to memory seperate them by time")
       for i in range(len(self.selectionQuerys)):
           layname = self.time_pickup_start[i].lstrip(' ').replace(":", "") + '_' + self.time_pickup_end[i].lstrip(' ').replace(":", "") + '_customers'
           fileName = layname + '.shp'
           path = os.path.join(self.outputPath, fileName)
           #print("costomerByTimePath:" , path)
           #print(self.selectionQuerys[i])
           arcpy.SelectLayerByAttribute_management(out_Layer,
                                        'NEW_SELECTION', self.selectionQuerys[i])
          # print 'Queries: ' + self.selectionQuerys[i]
           matchcount = int(arcpy.GetCount_management(out_Layer).getOutput(0))
          # print 'match count: ' + str(matchcount)
           arcpy.CopyFeatures_management(out_Layer, path)
           self.featuresList.append(out_Layer)
           
           arcpy.MakeFeatureLayer_management(path, layname)
           self.featuresList.append(layname)
           self.print_console('Layer: ' + layname + ' successfully added to layers')
           customLayname.append(layname) 
           self.print_console('Adding Buffer Data and selct by location:\n')
       filePaths = []
       if self.dataVar == 1:
           for node in self.wkdayData:
               filePaths.append(os.path.join(os.path.abspath("Data/wkday"), node))
       elif self.dataVar == 2:
           for node in self.satData:
               filePaths.append(os.path.join(os.path.abspath("Data/sat"), node))
       elif self.dataVar == 3:
           for node in self.sunData:
               filePaths.append(os.path.join(os.path.abspath("Data/sun"), node))
       
       for filepath in filePaths:
           path = os.path.join(os.path.abspath(''), filepath)
           #bufferPath.append(path)
           bufferName = os.path.basename(path).strip('.shp')
           print 'path:' + path
           arcpy.MakeFeatureLayer_management(path, bufferName)
           self.featuresList.append(bufferName)
           #print 'Buffer: ' + bufferName + 'successfully added to layers'
           index = filePaths.index(filepath)        
 #   COMPLETELY_WITHIN
           #print customLayname[index] + ' and ' + bufferName
           arcpy.SelectLayerByLocation_management(customLayname[index], 'COMPLETELY_WITHIN', bufferName)
           
           
           arcpy.SelectLayerByAttribute_management(customLayname[index], "SWITCH_SELECTION")
           underscore = bufferName.find("_", bufferName.find("_") + 1)
           
           resultName = os.path.normpath(os.path.join(self.result_path, bufferName[0:underscore + 1] + "result_d.shp"))
           #print 'resName: ' + resultName
           arcpy.CopyFeatures_management(customLayname[index], resultName)
           self.featuresList.append(customLayname[index])
           self.print_console('File:' + resultName + ' successfully exported!')
       #self.cleanup()    
       self.runTime = self.runTime + 1
       self.selectionQuerys = []
                
        
    
           
        
    
      
      
      
      

def main():
   
   CustomerFinder().mainloop()   

if __name__ == "__main__":
   main()
